const express = require('express');
const { body, validationResult } = require('express-validator');
const { Op } = require('sequelize');
const { asyncHandler } = require('../middleware/errorHandler');
const { success, error, checkEmail, encryptPassword, verifyPassword } = require('../utils/common');
const { authenticateToken } = require('../middleware/auth');
const User = require('../models/User');

const router = express.Router();

/**
 * 获取用户信息
 */
router.get('/profile', authenticateToken, asyncHandler(async (req, res) => {
  const user = await User.findByPk(req.user.id, {
    attributes: { exclude: ['password'] }
  });

  if (!user) {
    return res.status(404).json(error('用户不存在'));
  }

  res.json(success(user, '获取成功'));
}));

/**
 * 更新用户信息
 */
router.put('/profile', authenticateToken, [
  body('nickname').optional().isLength({ min: 1, max: 50 }).withMessage('昵称长度必须在1-50位之间'),
  body('email').optional().isEmail().withMessage('邮箱格式不正确'),
  body('bio').optional().isLength({ max: 500 }).withMessage('个人简介不能超过500字')
], asyncHandler(async (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json(error(errors.array()[0].msg));
  }

  const { nickname, email, bio, gender, birthday, address, school, grade } = req.body;

  // 检查邮箱是否已被其他用户使用
  if (email) {
    const existingUser = await User.findOne({
      where: {
        [Op.and]: [
          { email },
          {
            id: { [Op.ne]: req.user.id }
          }
        ]
      }
    });

    if (existingUser) {
      return res.status(400).json(error('邮箱已被使用'));
    }
  }

  // 更新用户信息
  const updateData = {};
  if (nickname) updateData.nickname = nickname;
  if (email) updateData.email = email;
  if (bio !== undefined) updateData.bio = bio;
  if (gender) updateData.gender = gender;
  if (birthday) updateData.birthday = birthday;
  if (address) updateData.address = address;
  if (school) updateData.school = school;
  if (grade) updateData.grade = grade;

  await User.update(updateData, { where: { id: req.user.id } });

  res.json(success(null, '更新成功'));
}));

/**
 * 修改密码
 */
router.put('/password', authenticateToken, [
  body('old_password').notEmpty().withMessage('原密码不能为空'),
  body('new_password').isLength({ min: 6, max: 20 }).withMessage('新密码长度必须在6-20位之间')
], asyncHandler(async (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json(error(errors.array()[0].msg));
  }

  const { old_password, new_password } = req.body;

  // 获取用户信息
  const user = await User.findByPk(req.user.id);
  if (!user) {
    return res.status(404).json(error('用户不存在'));
  }

  // 验证原密码
  const isValidPassword = await verifyPassword(old_password, user.password);
  if (!isValidPassword) {
    return res.status(400).json(error('原密码错误'));
  }

  // 验证新密码强度
  if (!checkPass(new_password)) {
    return res.status(400).json(error('新密码必须包含字母和数字'));
  }

  // 更新密码
  const hashedPassword = await encryptPassword(new_password);
  await user.update({ password: hashedPassword });

  res.json(success(null, '密码修改成功'));
}));

/**
 * 上传头像
 */
router.post('/avatar', asyncHandler(async (req, res) => {
  // TODO: 实现文件上传功能
  res.json(success({ avatar: 'upload/avatar/default.png' }, '头像上传成功'));
}));

/**
 * 签到
 */
router.post('/sign', asyncHandler(async (req, res) => {
  const user = await User.findByPk(req.user.id);
  if (!user) {
    return res.status(404).json(error('用户不存在'));
  }

  // 检查今日是否已签到
  const today = new Date().toDateString();
  const lastSignDate = user.last_sign_date ? new Date(user.last_sign_date).toDateString() : null;

  if (lastSignDate === today) {
    return res.status(400).json(error('今日已签到'));
  }

  // 更新签到信息
  const newSign = user.sign + 1;
  await user.update({
    sign: newSign,
    last_sign_date: new Date(),
    coin: user.coin + 10 // 签到奖励10金币
  });

  res.json(success({
    sign: newSign,
    coin: user.coin + 10
  }, '签到成功，获得10金币'));
}));

/**
 * 获取用户统计信息
 */
router.get('/stats', asyncHandler(async (req, res) => {
  const user = await User.findByPk(req.user.id, {
    attributes: ['id', 'level', 'experience', 'coin', 'votes', 'sign']
  });

  if (!user) {
    return res.status(404).json(error('用户不存在'));
  }

  res.json(success(user, '获取成功'));
}));

module.exports = router; 